import api from '../../utils/api';
import util from '../../utils/index';

Page({
    data:{
        productId:'',
        price:0,
        loading:false,
        productNum:'1'
    },

    onLoad:function (options) {
        console.log(options)
        this.setData({
            productId:options.id,
            price: options.price
        })
    },

    //点击form表单执行
    bindFormSubmit:function (e) {

        let formId = e.detail.formId;


        console.log(formId);


        this.setData({
            "loading":true
        })

        var that = this;
        let data = e.detail.value;
        data['productId'] = this.data.productId;
        data['formId'] = formId;


        // 参数验证
        if(!e.detail.value.productNum || !e.detail.value.buyerAddress || !e.detail.value.buyerPhone){
            wx.showToast({
                title: '订单信息不完整',
                icon: 'fail',
                duration: 1000
            })
            that.setData({
                "loading":false
            })
            return;
        }

        util.request({
            'url':api.createOrderUrl,
            method: 'POST',
            header: {
                'content-type': 'application/json',
                'x-auth-token': wx.getStorageSync('sessionId')
            },
            data: data}).then(res=>{
            if(res && res.errorCode === 0){
                wx.showToast({
                    title: '购买成功!',
                    icon: 'success',
                    duration: 1000
                })

                // 通知用户


                setTimeout(function () {
                    wx.switchTab({
                        url: "/pages/index/index"
                    });
                }, 1000)
            }else {
                wx.showToast({
                    title: '服务器异常',
                    icon: 'fail',
                    duration: 1000
                })

                that.setData({
                    "loading":false
                })
            }
        })
    },

    productNumInput:function (e) {
        this.setData({
            productNum: e.detail.value
        })
    }
})